import esda
import libpysal as lps
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sbn
import geopandas as gpd
plt.rcParams['font.sans-serif'] = ['KaiTi']
plt.rcParams['axes.unicode_minus'] = False
# 空间权重矩阵的选择 Rook or Queen
def s_weights(df, w_type='Rook'):
    if w_type != 'Rook':
        w = lps.weights.Queen.from_dataframe(df)
        w.transform = 'r'
    else:
        w = lps.weights.Rook.from_dataframe(df)
        w.transform = 'r'
    return w


# 空间滞后
def Spatial_lay(df, w):
    y = df['count']
    ylag = lps.weights.lag_spatial(w, y)
    df['lag_count'] = ylag
    fig, ax = plt.subplots(1, 2, figsize=(2.16 * 4, 4))
    df.plot(column='count', ax=ax[0], edgecolor='white',linewidth=0.01,
            scheme="quantiles", k=5, cmap='GnBu')
    ax[0].axis(df.total_bounds[np.asarray([0, 2, 1, 3])])
    ax[0].set_title("count")
    df.plot(column='lag_count', ax=ax[1], edgecolor='white',linewidth=0.01,
            scheme='quantiles', cmap='GnBu', k=5)
    ax[1].axis(df.total_bounds[np.asarray([0, 2, 1, 3])])
    ax[1].set_title("Spatial Lag count")
    ax[0].axis('off')
    ax[1].axis('off')
    plt.show()
    #mpld3.show()
    #mpld3.fig_to_html(fig)
    return ylag


# 全局空间自相关
def Global_Spatial_Autocorrelation(df, w,keyword='infected_count'):
    y = df[keyword]
    mi = esda.moran.Moran(y, w)
    print('Moran‘s I ', mi.I)
    print('p ', mi.p_sim)
    sbn.kdeplot(mi.sim, shade=True)
    plt.vlines(mi.I, 0, 1, color='r')
    plt.vlines(mi.EI, 0, 1)
    plt.xlabel("Moran's I")
    return mi.I


# 局部空间自相关
def Local_Spatial_Autocorrelation(df, w,keyword='infected_count'):
    y = df[keyword]
    li = esda.moran.Moran_Local(y, w)
    sig = 1 * (li.p_sim < 0.05)
    hotspot = 1 * (sig * li.q == 1)
    coldspot = 3 * (sig * li.q == 3)
    doughnut = 2 * (sig * li.q == 2)
    diamond = 4 * (sig * li.q == 4)
    spots = hotspot + coldspot + doughnut + diamond
    spot_labels = ['0 ns', '1 h-h', '2 h-l', '3 l-l', '4 l-h']
    labels = [spot_labels[i] for i in spots]
    from matplotlib import colors
    hmap = colors.ListedColormap(['lightgrey', 'lightblue', 'red', 'blue', 'pink'])
    fig, ax = plt.subplots(1, figsize=(9, 9))
    df.assign(cl=labels).plot(column='cl', categorical=True, k=4, cmap=hmap, linewidth=0.1, ax=ax, edgecolor='white',
                              legend=True)
    ax.set_axis_off()
    plt.show()
    #mpld3.show()
    #mpld3.fig_to_html(fig)
    return li

gdf=gpd.read_file('武汉GWR.geojson')
w=s_weights(gdf,"Queen")
i=Global_Spatial_Autocorrelation(gdf,w)
il=Local_Spatial_Autocorrelation(gdf,w)
# DMC模型
# def